﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using General.Core.Data;
using General.Entities.Models;
using General.Entities.ViewData.SystemConfig;
using Microsoft.EntityFrameworkCore;

namespace General.Services.SystemConfig
{
    public class SystemConfigService:ISystemConfigService
    {
        private readonly IRepository<tc_sysconftype> tc_SysconftypeRepository;
        private readonly IRepository<tc_sysconfig> tc_SysconfigRepository;

        public SystemConfigService(IRepository<tc_sysconftype> tc_sysconftypeRepository,
            IRepository<tc_sysconfig> tc_sysconfigRepository)
        {
            tc_SysconftypeRepository = tc_sysconftypeRepository;
            tc_SysconfigRepository = tc_sysconfigRepository;
        }

        /// <summary>
        /// 获取设置类别列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<tc_sysconftype>> GetTypeList()
        {
            return await tc_SysconftypeRepository.GetAllAsync().OrderBy(x=>x.sort).ToListAsync();
        }

        /// <summary>
        /// 根据标识获取配置信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task<tc_sysconfig> GetConfigInfoByCode(string code)
        {
            return await tc_SysconfigRepository.GetAsync(x=>x.code == code);
        }

        /// <summary>
        /// 获取所有配置信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task<List<tc_sysconfig>> GetAllConfigInfo()
        {
            return await tc_SysconfigRepository.GetAllAsync().OrderBy(x=>x.sort).ToListAsync();
        }

        /// <summary>
        /// 添加配置信息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<int> AddConfigData(tc_sysconfig data)
        {
            data.createtime = DateTime.Now;
            return await tc_SysconfigRepository.insertAsync(data);
        }


        /// <summary>
        /// 修改配置信息
        /// </summary>
        /// <param name="tid"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task EditConfigData(int tid, List<SystemConfigModel> data)
        {
            var list = await tc_SysconfigRepository.Table.Where(x=>x.tid == tid).ToListAsync();
            foreach (var item in data)
            {
                var model = list.Where(x=>x.code == item.key).FirstOrDefault();
                if (model != null)
                {
                    model.value = item.value;
                }
            }
            await tc_SysconfigRepository.UpdateListAsync(list);
        }

    }
}
